package com.geralt.im.jsonparser.impl;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.geralt.im.jsonparser.IjsonParser;
import com.geralt.im.protocol.Request;
import com.geralt.im.protocol.Response;
import com.geralt.im.tool.JsonTool;

public class ResponseJsonParser implements IjsonParser {

	private static Map<String, String> map = new HashMap<String, String>();
	static {
		try {
			InputStream is = IjsonParser.class.getClassLoader()
					.getResourceAsStream("responseJsonParse.properties");
			Properties property = new Properties();
			property.load(is);
			Set<Object> kSet = property.keySet();
			for (Object key : kSet) {
				map.put((String) key, property.getProperty((String) key));
			}
			// System.out.println("Map:"+map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Object parse(String jsonString) {
		Response response = null;
		try {
			JsonTool jt = JsonTool.getInstance();
			response = (Response) JsonTool.getInstance().stringToObject(
					jsonString, Response.class);
			Set<String> keyset = response.getParameter().keySet();
			for (String key : keyset) {
				if (map.containsKey(key)) {
					// System.out.println("getKey:"+key);
					String className = map.get(key);
					Class clz = Class.forName(className);
					String objToString = jt.objectToString(response
							.getParameter().get(key));
					Object k = jt.stringToObject(objToString, clz);
					response.getParameter().put(key, k);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

}
